// 主导航页面功能脚本
class ToolNavigator {
    constructor() {
        this.tools = [];
        this.filteredTools = [];
        this.activeCategory = 'all';
        this.searchQuery = '';
        
        this.init();
    }
    
    init() {
        this.cacheElements();
        this.bindEvents();
        this.loadTools();
        this.initializeFilters();
    }
    
    cacheElements() {
        this.searchInput = document.getElementById('search-input');
        this.toolsGrid = document.getElementById('tools-grid');
        this.categoryBtns = document.querySelectorAll('.category-btn');
        this.toolCards = document.querySelectorAll('.tool-card');
    }
    
    bindEvents() {
        // 搜索功能
        this.searchInput?.addEventListener('input', (e) => {
            this.searchQuery = e.target.value.toLowerCase().trim();
            this.filterTools();
        });
        
        // 分类过滤
        this.categoryBtns.forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.setActiveCategory(e.target.dataset.category);
            });
        });
        
        // 工具卡片点击事件
        this.toolCards.forEach(card => {
            if (card.classList.contains('available')) {
                const link = card.querySelector('.tool-link');
                if (link && !link.classList.contains('disabled')) {
                    card.addEventListener('click', (e) => {
                        if (e.target.tagName !== 'A') {
                            link.click();
                        }
                    });
                    card.style.cursor = 'pointer';
                }
            }
        });
        
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.key === '/' && !e.ctrlKey && !e.metaKey) {
                e.preventDefault();
                this.searchInput?.focus();
            }
            
            if (e.key === 'Escape') {
                this.clearSearch();
            }
        });
        
        // 响应式处理
        window.addEventListener('resize', () => {
            this.handleResize();
        });
    }
    
    loadTools() {
        this.tools = Array.from(this.toolCards).map(card => ({
            element: card,
            title: card.querySelector('h3')?.textContent || '',
            description: card.querySelector('p')?.textContent || '',
            category: card.dataset.category || '',
            keywords: card.dataset.keywords || '',
            available: card.classList.contains('available')
        }));
        
        this.filteredTools = [...this.tools];
    }
    
    setActiveCategory(category) {
        this.activeCategory = category;
        
        // 更新按钮状态
        this.categoryBtns.forEach(btn => {
            btn.classList.toggle('active', btn.dataset.category === category);
        });
        
        this.filterTools();
    }
    
    filterTools() {
        this.filteredTools = this.tools.filter(tool => {
            const matchesCategory = this.activeCategory === 'all' || 
                                  tool.category === this.activeCategory;
            
            const matchesSearch = !this.searchQuery || 
                                this.matchesSearchQuery(tool);
            
            return matchesCategory && matchesSearch;
        });
        
        this.updateDisplay();
    }
    
    matchesSearchQuery(tool) {
        const searchFields = [
            tool.title,
            tool.description,
            tool.keywords,
            tool.category
        ].join(' ').toLowerCase();
        
        return searchFields.includes(this.searchQuery);
    }
    
    updateDisplay() {
        let visibleCount = 0;
        
        this.tools.forEach(tool => {
            const isVisible = this.filteredTools.includes(tool);
            
            if (isVisible) {
                tool.element.classList.remove('filtered-out', 'hidden');
                visibleCount++;
            } else {
                tool.element.classList.add('filtered-out');
                setTimeout(() => {
                    if (tool.element.classList.contains('filtered-out')) {
                        tool.element.classList.add('hidden');
                    }
                }, 300);
            }
        });
        
        // 显示空状态
        this.toggleNoResults(visibleCount === 0);
        
        // 更新统计信息
        this.updateStats();
    }
    
    toggleNoResults(show) {
        let noResultsElement = this.toolsGrid.querySelector('.no-results');
        
        if (show && !noResultsElement) {
            noResultsElement = document.createElement('div');
            noResultsElement.className = 'no-results';
            noResultsElement.innerHTML = `
                <h3>😔 未找到匹配的工具</h3>
                <p>尝试使用其他关键词或选择不同的分类</p>
            `;
            this.toolsGrid.appendChild(noResultsElement);
        } else if (!show && noResultsElement) {
            noResultsElement.remove();
        }
    }
    
    updateStats() {
        const availableCount = this.filteredTools.filter(tool => tool.available).length;
        const totalCount = this.filteredTools.length;
        
        // 更新头部统计信息
        const statElement = document.querySelector('.header-stats .stat strong');
        if (statElement) {
            statElement.textContent = totalCount;
        }
    }
    
    clearSearch() {
        this.searchInput.value = '';
        this.searchQuery = '';
        this.filterTools();
        this.searchInput.blur();
    }
    
    initializeFilters() {
        // 初始化时应用当前过滤器
        this.filterTools();
        
        // 添加搜索提示
        this.addSearchHints();
    }
    
    addSearchHints() {
        if (this.searchInput) {
            this.searchInput.setAttribute('title', '按 / 键快速聚焦搜索框');
            
            // 添加搜索建议
            const hints = [
                '搜索工具名称、功能或关键词',
                '尝试搜索: JSON, 图表, 压缩, OCR',
                '支持中文和英文搜索',
                '按 ESC 键清空搜索'
            ];
            
            let hintIndex = 0;
            const originalPlaceholder = this.searchInput.placeholder;
            
            this.searchInput.addEventListener('focus', () => {
                this.searchInput.placeholder = hints[hintIndex];
                hintIndex = (hintIndex + 1) % hints.length;
            });
            
            this.searchInput.addEventListener('blur', () => {
                if (!this.searchInput.value) {
                    this.searchInput.placeholder = originalPlaceholder;
                }
            });
        }
    }
    
    handleResize() {
        // 响应式处理逻辑
        const isMobile = window.innerWidth <= 768;
        
        if (isMobile) {
            // 移动端优化
            this.optimizeForMobile();
        } else {
            // 桌面端优化
            this.optimizeForDesktop();
        }
    }
    
    optimizeForMobile() {
        // 移动端特定优化
        this.categoryBtns.forEach(btn => {
            btn.style.fontSize = '0.85rem';
        });
    }
    
    optimizeForDesktop() {
        // 桌面端特定优化
        this.categoryBtns.forEach(btn => {
            btn.style.fontSize = '';
        });
    }
    
    // 公共方法：获取工具统计信息
    getStats() {
        const available = this.tools.filter(tool => tool.available).length;
        const comingSoon = this.tools.filter(tool => !tool.available).length;
        const categories = [...new Set(this.tools.map(tool => tool.category))];
        
        return {
            total: this.tools.length,
            available,
            comingSoon,
            categories: categories.length,
            filtered: this.filteredTools.length
        };
    }
    
    // 公共方法：导航到工具
    navigateToTool(toolName) {
        const tool = this.tools.find(t => 
            t.title.toLowerCase().includes(toolName.toLowerCase())
        );
        
        if (tool && tool.available) {
            const link = tool.element.querySelector('.tool-link');
            if (link && !link.classList.contains('disabled')) {
                link.click();
            }
        }
    }
}

// 工具使用统计
class ToolAnalytics {
    constructor() {
        this.stats = this.loadStats();
    }
    
    loadStats() {
        try {
            return JSON.parse(localStorage.getItem('toolnav_stats') || '{}');
        } catch {
            return {};
        }
    }
    
    saveStats() {
        try {
            localStorage.setItem('toolnav_stats', JSON.stringify(this.stats));
        } catch (e) {
            console.warn('无法保存统计数据:', e);
        }
    }
    
    trackToolUsage(toolName) {
        this.stats[toolName] = (this.stats[toolName] || 0) + 1;
        this.stats.lastUsed = Date.now();
        this.saveStats();
    }
    
    getPopularTools() {
        return Object.entries(this.stats)
            .filter(([key]) => key !== 'lastUsed')
            .sort(([,a], [,b]) => b - a)
            .slice(0, 5);
    }
}

// 主题管理器
class ThemeManager {
    constructor() {
        this.currentTheme = this.loadTheme();
        this.applyTheme();
    }
    
    loadTheme() {
        return localStorage.getItem('toolnav_theme') || 'default';
    }
    
    saveTheme() {
        localStorage.setItem('toolnav_theme', this.currentTheme);
    }
    
    applyTheme() {
        document.body.setAttribute('data-theme', this.currentTheme);
    }
    
    toggleTheme() {
        this.currentTheme = this.currentTheme === 'default' ? 'dark' : 'default';
        this.applyTheme();
        this.saveTheme();
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 创建应用实例
    window.toolNavigator = new ToolNavigator();
    window.toolAnalytics = new ToolAnalytics();
    window.themeManager = new ThemeManager();
    
    // 添加工具链接点击统计
    document.querySelectorAll('.tool-link:not(.disabled)').forEach(link => {
        link.addEventListener('click', (e) => {
            const toolCard = e.target.closest('.tool-card');
            const toolName = toolCard?.querySelector('h3')?.textContent;
            if (toolName) {
                window.toolAnalytics.trackToolUsage(toolName);
            }
        });
    });
    
    // 添加页面可见性检测
    document.addEventListener('visibilitychange', () => {
        if (!document.hidden) {
            // 页面重新可见时更新数据
            window.toolNavigator.updateStats();
        }
    });
    
    // 添加错误处理
    window.addEventListener('error', (e) => {
        console.error('页面错误:', e.error);
    });
    
    // 性能优化：预加载热门工具
    setTimeout(() => {
        const popularTools = window.toolAnalytics.getPopularTools();
        popularTools.forEach(([toolName]) => {
            // 预加载逻辑（如果需要）
        });
    }, 1000);
});

// 导出全局方法
window.ToolNav = {
    search: (query) => window.toolNavigator?.clearSearch() || window.toolNavigator?.searchInput?.focus(),
    navigate: (toolName) => window.toolNavigator?.navigateToTool(toolName),
    stats: () => window.toolNavigator?.getStats(),
    toggleTheme: () => window.themeManager?.toggleTheme()
}; 